package com.bootdo.order.utils;

import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author admin
 * @Desc
 * @date 2020/2/23
 *
 */
public class OrderSequence {

    private static final Logger logger = LoggerFactory.getLogger(OrderSequence.class);

    /**
     * 订单前缀
     */
    private static final String ORDERPREFIX = "TC";
    /**
     * 时间戳
     */
    private static final String FORMAT = "yyyyMMddHHmmss";

    private static final String FORMATSTR = "%06d";
    /**
     * 数字随机
     */
    private static final AtomicInteger ATOMICNUM = new AtomicInteger();

    private static String lastId;

    /**
     * @return
     * @author yugenhai
     */
    @NotNull
    public synchronized static String createOrderSnRandom() {
        return AbstractOrderSequenceRandomInner.createOrderSnRandomInner();
    }

    /**
     * 创建订单号<svsp + yyyy-mm-dd + Random>
     *
     * @author yugenhai
     */
    private final static class AbstractOrderSequenceRandomInner {

        @PostConstruct
        public void initMaxNum(){
            try{
                if (StringUtils.isBlank(lastId)){
                    ATOMICNUM.set(1);
                } else {
                    String nowDate = DateUtils.format(new Date(), "yyyyMMdd");
                    String lastDate = lastId.substring(2, 10);
                    if (!nowDate.equals(lastDate)){
                        ATOMICNUM.set(1);
                    }
                }
            }catch(Exception e){
                logger.error("初始化获取分组编号最大值异常",e);
            }
        }

        private synchronized static String createOrderSnRandomInner() {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat(FORMAT);
            lastId = ORDERPREFIX + sdf.format(date) + String.format(FORMATSTR, ATOMICNUM.incrementAndGet());
            return lastId;
        }
    }
}
